<template>
  <div class="add-outbound-page">
    <!-- 页面头部 -->
    <div class="page-header">
      <h2>{{ isEdit ? '修改出库单' : '新增出库' }}</h2>
      <div class="header-actions">
        <el-button @click="handleBack">返回</el-button>
      </div>
    </div>

    <!-- 基本信息 -->
    <div class="form-section">
      <h3>基本信息</h3>
      <el-form :model="form" :rules="rules" ref="outboundForm" label-width="120px">
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="出库单号" prop="boundCode">
              <el-input v-model="form.boundCode" :disabled="isEdit" placeholder="系统自动生成"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="制单人" prop="creator">
              <el-input v-model="form.creator" placeholder="--请输入制单人--" style="width: 100%">
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="单据日期" prop="createTime">
              <el-date-picker
                v-model="form.createTime"
                type="date"
                placeholder="请选择时间"
                style="width: 100%"
                format="yyyy-MM-dd"
                value-format="yyyy-MM-dd"
              ></el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="供应商" prop="supplierId">
              <el-select v-model="form.supplierId" placeholder="--请--" style="width: 100%">
                <el-option
                  v-for="supplier in suppliers"
                  :key="supplier.supplierId"
                  :label="supplier.supplierName"
                  :value="supplier.supplierId"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="出库仓库" prop="warehouseId">
              <el-select v-model="form.warehouseId" placeholder="--请选择仓库--" style="width: 100%">
                <el-option
                  v-for="warehouse in warehouses"
                  :key="warehouse.warehouseId"
                  :label="warehouse.warehouseName"
                  :value="warehouse.warehouseId"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="小区" prop="communityId">
              <el-select v-model="form.communityId" placeholder="--请选择小区--" style="width: 100%">
                <el-option
                  v-for="community in communities"
                  :key="community.communityId"
                  :label="community.communityName"
                  :value="community.communityId"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="操作状态" prop="boundStatus">
              <el-select v-model="form.boundStatus" placeholder="--请选择状态--" style="width: 100%">
                <el-option label="入库" :value="1"></el-option>
                <el-option label="出库" :value="2"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" placeholder="请输入备注信息" type="textarea" :rows="2"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>

    <!-- 详细出库列表（仅新增模式显示） -->
    <div class="form-section" v-if="!isEdit">
      <div class="section-header">
        <h3>详细出库列表</h3>
        <el-button type="primary" icon="el-icon-plus" @click="handleAddMaterial">+添加</el-button>
      </div>
      
      <el-table :data="boundInfoList" border style="width: 100%; margin-bottom: 20px;">
        <el-table-column label="材料名称" width="150">
          <template slot-scope="scope">
            {{ scope.row.materialName }}
          </template>
        </el-table-column>
        <el-table-column label="品牌" width="120">
          <template slot-scope="scope">
            {{ scope.row.brand }}
          </template>
        </el-table-column>
        <el-table-column label="规格型号" width="150">
          <template slot-scope="scope">
            {{ scope.row.specificationModel }}
          </template>
        </el-table-column>
        <el-table-column label="单位" width="80">
          <template slot-scope="scope">
            {{ scope.row.unit }}
          </template>
        </el-table-column>
        <el-table-column label="成本价" width="120">
          <template slot-scope="scope">
            <el-input
              v-model="scope.row.costPrice"
              placeholder="材料价格"
              @input="calculateTotal(scope.row)"
              type="number"
              readonly
            ></el-input>
          </template>
        </el-table-column>
        <el-table-column label="数量" width="120">
          <template slot-scope="scope">
            <el-input
              v-model="scope.row.quantity"
              placeholder="请输入数量"
              @input="calculateTotal(scope.row)"
              type="number"
            ></el-input>
          </template>
        </el-table-column>
        <el-table-column label="合计" width="120">
          <template slot-scope="scope">
            {{ scope.row.totalPrice || '0.00' }}
          </template>
        </el-table-column>
        <el-table-column label="备注" width="150">
          <template slot-scope="scope">
            <el-input v-model="scope.row.remark" placeholder="请输入备注"></el-input>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="100">
          <template slot-scope="scope">
            <el-button type="text" size="small" @click="handleDeleteMaterial(scope.$index)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 详细出库列表（编辑模式只读显示） -->
    <div class="form-section" v-if="isEdit">
      <h3>详细出库列表</h3>
      <el-table :data="boundInfoList" border style="width: 100%; margin-bottom: 20px;">
        <el-table-column label="材料名称" width="150">
          <template slot-scope="scope">
            {{ scope.row.materialName }}
          </template>
        </el-table-column>
        <el-table-column label="品牌" width="120">
          <template slot-scope="scope">
            {{ scope.row.brand }}
          </template>
        </el-table-column>
        <el-table-column label="规格型号" width="150">
          <template slot-scope="scope">
            {{ scope.row.specificationModel }}
          </template>
        </el-table-column>
        <el-table-column label="单位" width="80">
          <template slot-scope="scope">
            {{ scope.row.unit }}
          </template>
        </el-table-column>
        <el-table-column label="成本价" width="120">
          <template slot-scope="scope">
            {{ scope.row.costPrice || '0.00' }}
          </template>
        </el-table-column>
        <el-table-column label="数量" width="120">
          <template slot-scope="scope">
            {{ scope.row.quantity || '0' }}
          </template>
        </el-table-column>
        <el-table-column label="合计" width="120">
          <template slot-scope="scope">
            {{ scope.row.totalPrice || '0.00' }}
          </template>
        </el-table-column>
        <el-table-column label="备注" width="150">
          <template slot-scope="scope">
            {{ scope.row.remark || '--' }}
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 操作按钮 -->
    <div class="form-actions">
      <el-button @click="handleCancel">取消</el-button>
      <el-button type="primary" @click="handleSubmit" :loading="submitting">{{ isEdit ? '修改' : '保存' }}</el-button>
    </div>

    <!-- 添加材料弹窗 -->
    <el-dialog
      title="添加材料"
      :visible.sync="materialDialogVisible"
      width="70%"
      :close-on-click-modal="false"
    >
      <AddMaterialDialog
        :visible.sync="materialDialogVisible"
        @confirm="handleMaterialConfirm"
      />
    </el-dialog>
  </div>
</template>

<script>
import { boundApi } from '@/api/bound'
import { supplierApi } from '@/api/supplier'
import { warehouseApi } from '@/api/warehouse'
import AddMaterialDialog from './components/AddMaterialDialog.vue'

export default {
  name: 'AddOutbound',
  components: {
    AddMaterialDialog
  },
  data() {
    return {
      submitting: false,
      suppliers: [],
      warehouses: [],
      communities: [],
      materialDialogVisible: false,
      isEdit: false,
      boundId: '', // 编辑时的出库单ID
      form: {
        boundCode: '',
        creator: '',
        createTime: '',
        supplierId: '',
        warehouseId: '',
        communityId: '',
        boundStatus: 2, // 默认出库状态
        remark: ''
      },
      boundInfoList: [],
      rules: {
        creator: [
          { required: true, message: '请输入制单人', trigger: 'blur' }
        ],
        createTime: [
          { required: true, message: '请选择单据日期', trigger: 'change' }
        ],
        supplierId: [
          { required: true, message: '请选择供应商', trigger: 'change' }
        ],
        warehouseId: [
          { required: true, message: '请选择仓库', trigger: 'change' }
        ],
        boundStatus: [
          { required: true, message: '请选择操作状态', trigger: 'change' }
        ],
        communityId: [
          { required: true, message: '请选择小区', trigger: 'change' }
        ]
      }
    }
  },
  created() {
    this.initForm()
    this.loadSuppliers()
    this.loadWarehouses()
    this.loadCommunities()
    
    // 检查是否是编辑模式
    if (this.$route.params.id) {
      this.isEdit = true
      this.boundId = this.$route.params.id
      this.loadBoundDetail()
    } else {
      this.generateBoundCode()
    }
  },
  methods: {
    // 初始化表单
    initForm() {
      // 设置默认值
      this.form.creator = 'admin'
      this.form.createTime = this.formatDate(new Date())
      this.form.boundStatus = 2 // 默认出库状态
    },

    // 加载供应商列表
    async loadSuppliers() {
      try {
        const response = await supplierApi.getAllSuppliers()
        if (response.code === 200) {
          this.suppliers = response.data || []
        }
      } catch (error) {
        console.error('加载供应商列表失败:', error)
      }
    },

    // 加载仓库列表
    async loadWarehouses() {
      try {
        console.log('开始加载仓库列表...')
        const response = await warehouseApi.getAllWarehouses()
        console.log('仓库列表响应:', response)
        if (response.code === 200) {
          this.warehouses = response.data || []
          console.log('仓库列表数据:', this.warehouses)
        } else {
          console.error('加载仓库列表失败:', response.message)
          this.$message.error(response.message || '加载仓库列表失败')
        }
      } catch (error) {
        console.error('加载仓库列表失败:', error)
        this.$message.error('加载仓库列表失败，请稍后重试')
      }
    },

    // 加载小区列表
    async loadCommunities() {
      try {
        const response = await warehouseApi.getAllCommunities()
        if (response.code === 200) {
          this.communities = response.data || []
        }
      } catch (error) {
        console.error('加载小区列表失败:', error)
      }
    },

    // 生成出库单号
    async generateBoundCode() {
      try {
        const response = await boundApi.generateBoundCode()
        if (response.code === 200) {
          this.form.boundCode = response.data
        }
      } catch (error) {
        console.error('生成出库单号失败:', error)
        // 如果生成失败，使用时间戳作为单号
        this.form.boundCode = 'OB' + Date.now()
      }
    },

    // 加载出库单详情（编辑模式）
    async loadBoundDetail() {
      try {
        const response = await boundApi.getBoundById(this.boundId)
        if (response.code === 200) {
          const data = response.data
          this.form = {
            boundCode: data.boundCode || '',
            creator: data.creator || '',
            createTime: data.creatorTime || '',
            supplierId: data.supplierId || '',
            warehouseId: data.warehouseId || '',
            communityId: data.communityId || '',
            boundStatus: data.boundStatus || 2,
            remark: data.boundDesc || ''
          }
          this.boundInfoList = data.boundInfoList || []
        } else {
          this.$message.error(response.message || '加载出库单详情失败')
        }
      } catch (error) {
        console.error('加载出库单详情失败:', error)
        this.$message.error('加载出库单详情失败，请稍后重试')
      }
    },

    // 添加材料
    handleAddMaterial() {
      this.materialDialogVisible = true
    },

    // 确认添加材料
    handleMaterialConfirm(materials) {
      materials.forEach(material => {
        this.boundInfoList.push({
          materialId: material.materialId,
          materialName: material.materialName,
          brand: material.materialBrand,
          specificationModel: material.materialSpecifications,
          unit: material.materialUnit,
          costPrice: material.materialPrice || '0.00', // 自动填充材料价格
          quantity: '',
          remark: material.materialDesc || ''
        })
      })
    },

    // 删除材料
    handleDeleteMaterial(index) {
      this.boundInfoList.splice(index, 1)
    },

    // 计算合计
    calculateTotal(row) {
      const costPrice = parseFloat(row.costPrice) || 0
      const quantity = parseFloat(row.quantity) || 0
      row.totalPrice = (costPrice * quantity).toFixed(2)
    },

    // 提交表单
    async handleSubmit() {
      try {
        await this.$refs.outboundForm.validate()
        
        // 新增模式需要检查材料列表
        if (!this.isEdit && this.boundInfoList.length === 0) {
          this.$message.warning('请至少添加一个材料')
          return
        }

        this.submitting = true

        let formData
        if (this.isEdit) {
          // 编辑模式：只提交基本信息
          formData = {
            boundId: this.boundId,
            boundCode: this.form.boundCode,
            creator: this.form.creator,
            createTime: this.form.createTime,
            supplierId: this.form.supplierId,
            warehouseId: this.form.warehouseId,
            communityId: this.form.communityId,
            boundStatus: this.form.boundStatus,
            remark: this.form.remark
          }
        } else {
          // 新增模式：提交完整信息
          formData = {
            ...this.form,
            boundInfoList: this.boundInfoList.map(item => ({
              materialId: item.materialId,
              materialNum: parseFloat(item.quantity) || 0
            }))
          }
        }

        let response
        if (this.isEdit) {
          // 编辑模式
          response = await boundApi.updateBound(formData)
        } else {
          // 新增模式
          response = await boundApi.addBound(formData)
        }

        if (response.code === 200) {
          this.$message.success(this.isEdit ? '修改成功' : '新增成功')
          this.handleBack()
        } else {
          this.$message.error(response.message || '操作失败')
        }
      } catch (error) {
        console.error('提交表单失败:', error)
        this.$message.error('操作失败，请稍后重试')
      } finally {
        this.submitting = false
      }
    },

    // 取消
    handleCancel() {
      this.$confirm('确定要取消吗？未保存的数据将丢失。', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.handleBack()
      }).catch(() => {
        // 用户取消
      })
    },

    // 返回
    handleBack() {
      this.$router.go(-1)
    },

    // 格式化日期
    formatDate(date) {
      if (!date) return ''
      const d = new Date(date)
      return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`
    }
  }
}
</script>

<style scoped>
.add-outbound-page {
  padding: 20px;
  background-color: #f0f2f5;
  min-height: 100vh;
}

/* 页面头部 */
.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding: 20px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.page-header h2 {
  margin: 0;
  color: #333;
  font-size: 24px;
  font-weight: 600;
}

.header-actions {
  display: flex;
  gap: 10px;
}

/* 表单区域 */
.form-section {
  background-color: #fff;
  border-radius: 8px;
  padding: 20px;
  margin-bottom: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.form-section h3 {
  margin: 0 0 20px 0;
  color: #333;
  font-size: 18px;
  font-weight: 600;
  border-bottom: 2px solid #409eff;
  padding-bottom: 10px;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.section-header h3 {
  margin: 0;
  border-bottom: none;
  padding-bottom: 0;
}

/* 操作按钮 */
.form-actions {
  display: flex;
  justify-content: center;
  gap: 20px;
  padding: 20px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

/* 表格样式 */
.el-table {
  border-radius: 8px;
  overflow: hidden;
}

.el-table th {
  background-color: #f5f7fa;
  color: #333;
  font-weight: 600;
}

.el-table td {
  padding: 12px 0;
}

/* 输入框样式 */
.el-input__inner {
  border-radius: 4px;
  border: 1px solid #dcdfe6;
  transition: border-color 0.2s cubic-bezier(0.645, 0.045, 0.355, 1);
}

.el-input__inner:focus {
  border-color: #409eff;
}

/* 按钮样式 */
.el-button {
  border-radius: 4px;
  font-weight: 500;
  transition: all 0.3s;
}

.el-button--primary {
  background-color: #409eff;
  border-color: #409eff;
}

.el-button--primary:hover {
  background-color: #66b1ff;
  border-color: #66b1ff;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .add-outbound-page {
    padding: 10px;
  }
  
  .page-header {
    flex-direction: column;
    gap: 15px;
    text-align: center;
  }
  
  .form-section {
    padding: 15px;
  }
  
  .section-header {
    flex-direction: column;
    gap: 15px;
    align-items: flex-start;
  }
  
  .form-actions {
    flex-direction: column;
    gap: 10px;
  }
}
</style>
